package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.UserCityRole;
import com.sanjishu.enterlab.electricity.sale.mapper.UserCityRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserCityRoleService {

    @Autowired
    private UserCityRoleMapper userCityRoleMapper;

    List<UserCityRole> findByUserId(Integer userId) {
        return userCityRoleMapper.findByUserId(userId);
    }

    public List<Integer> listCityIdByUserId(Integer userId) {
        List<UserCityRole> userCityRoleList = findByUserId(userId);
        List<Integer> cityIdList = new ArrayList<>();
        if (userCityRoleList != null && userCityRoleList.size() > 0) {
            for (UserCityRole userCityRole : userCityRoleList) {
                cityIdList.add(userCityRole.getCityId());
            }
        }
        return cityIdList;
    }

    @Transactional
    public Response saveSetting(Integer userId, Integer[] cityIds) {
        if(cityIds != null && cityIds.length > 0) {
            userCityRoleMapper.deleteByUserId(userId);
            for (Integer cityId : cityIds) {
                create(userId, cityId);
            }
        }
        return Response.buildSuccess("设置成功。");
    }

    public void create(Integer userId, Integer cityId) {
        UserCityRole userCityRole = new UserCityRole();
        userCityRole.setCityId(cityId);
        userCityRole.setUserId(userId);
        userCityRole.setCreatedAt(new Date());
        userCityRoleMapper.insert(userCityRole);
    }
}
